/*
 * Split up a path into a directory and a file name
 *
 * Copyright 2023 Odin Kroeger.
 *
 * This file is part of suCGI.
 *
 * suCGI is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * suCGI is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with suCGI. If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE 700

#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include "path.h"
#include "types.h"

char *
path_split(const char *const path, const char **const ptr,
           const ErrorFn errh)
{
    assert(path != NULL);

    size_t len = 0U;
    const char *pivot = path;
    const char *start = NULL;

    do {
        len = (*pivot == '/') ? 1U : strcspn(pivot, "/");

        start = pivot;
        const char *const end = &start[len];

        pivot = &end[strspn(end, "/")];
    } while (*start == '.' && len == 1U);

    char *seg = NULL;
    if (len > 0U) {
        errno = 0;
        seg = strndup(start, len);
        if (seg == NULL) {
            if (errh != NULL) {
                errh(EXIT_FAILURE, "strndup");
            }
            return NULL;
        }
    }

    if (ptr != NULL) {
        *ptr = pivot;
    }

    return seg;
}
